package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResponse<RoleVo> queryPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        String roleName = roleDto.getRoleName();
        PageHelper.startPage(pageNum, pageSize);
        Page page =roleMapper.queryPage(roleName);
        return PageResponse.of(page, RoleVo.class);
    }

    @Override
    public void insert(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<String> findCheckedResourcesByRoleId(Long roleId) {
        return roleMapper.findCheckedResourcesByRoleId(roleId);
    }

    @Override
    public void editAndStatusAndResource(RoleDto roleDto) {
        //1.修改角色+禁用启用
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //todo 该角色是否绑定用户 ---有绑定就不能更新和禁用
        if (ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            roleMapper.updateRole(role);
            return;
        }

        //2.点击接口是菜单编辑
        //3.把角色和菜单关联的数据全删除
        roleMapper.deleteByRoleId(roleDto.getId());
        //4.重新插入
        List<String> list = Arrays.asList(roleDto.getCheckedResourceNos());
        List<RoleResource> roleResourcesList = new ArrayList<>();

        for (String s : list){
            RoleResource roleResource = new RoleResource();
            roleResource.setResourceNo(s);
            roleResource.setRoleId(roleDto.getId());
            roleResource.setDataState("0");
            roleResourcesList.add(roleResource);
        }

        roleMapper.batchInsert(roleResourcesList);
    }

    @Override
    public List<RoleVo> inintRoles() {
        List<Role> roles = roleMapper.initRoles(null);
        return BeanUtil.copyToList(roles, RoleVo.class);
    }

}
























